﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Forms;
using HR60_PanelSoft.Model;
using HR60_PanelSoft.Model.BaseModel;
using HR60_PanelSoft.View.Base;

namespace HR60_PanelSoft.View.TabForms.ListItems
{
	public partial class SubExDeviceSelect : BaseFormControl
	{
		public SubExDeviceSelect()
		{
			InitializeComponent();
		}

		IList<CheckBox> subCbs = new List<CheckBox>();

		/// <summary>
		/// 填充数据
		/// </summary>
		/// <param name="device"></param>
		public void bindExDevice(Device device)
		{
			tblList.Controls.Clear();
			tblList.RowCount = device.childDevices.Count;
			ltlName.Text = device.nickName;

            //GC: 绑定设备到SubExDeviceSelect @s1
            /* s1 */
            this.Tag = (object)device; /* 将父设备实例绑定到控件 */
            /* end of s1 */
			foreach (Device sub in device.childDevices)
			{
				appendSub(sub);
			}
		}

		/// <summary>
		/// 添加分机
		/// </summary>
		/// <param name="sub"></param>
		private void appendSub(Device sub)
		{
			System.Windows.Forms.Panel panel = new System.Windows.Forms.Panel();
			Label ltlSubName = new Label();
			CheckBox cbSub = new CheckBox();
			subCbs.Add(cbSub);

			panel.Dock = DockStyle.Fill;
			panel.Margin = new Padding(0);
			panel.MaximumSize = new Size(0, 22);
			panel.Controls.Add(ltlSubName);
			panel.Controls.Add(cbSub);

			ltlSubName.MaximumSize = new Size(100, 32);
			ltlSubName.Text = sub.nickName;
			ltlSubName.Top = 4;
			ltlSubName.Padding = new Padding(10, 0, 0, 0);

			cbSub.Tag = sub.uuid;
			cbSub.CheckStateChanged += new EventHandler(cbSub_CheckStateChanged);
			cbSub.FlatStyle = FlatStyle.Flat;
			cbSub.Left = 150;
			cbSub.Top = -1;

			tblList.Controls.Add(panel);

			// 扩大checkbox的选择面
			panel.Click += new EventHandler(panel_Click);
			ltlSubName.Click += new EventHandler(ltlSubName_Click);
		}

		void ltlSubName_Click(object sender, EventArgs e)
		{
			panel_Click(((Control)sender).Parent, e);
		}

		void panel_Click(object sender, EventArgs e)
		{
			System.Windows.Forms.Panel panel = (System.Windows.Forms.Panel)sender;
			((CheckBox)panel.Controls[1]).Checked = !((CheckBox)panel.Controls[1]).Checked;
		}

		void cbSub_CheckStateChanged(object sender, EventArgs e)
		{
			//valueChange(this, e);
            valueChange_Normal(this, e);
		}

		// 重写Value属性，返回选择的设备的uuid列表
		public override object Value
		{
			get
			{
				IList<string> list = new List<string>();
				foreach (CheckBox cb in subCbs)
				{
					if (cb.Checked)
					{
						list.Add((string)cb.Tag);
					}
				}
				return list;
			}
			set
			{
				IList<string> list = (IList<string>)value;
				foreach (CheckBox cb in subCbs)
				{
					cb.Checked = false;
					foreach (string uuid in list)
					{
						if (uuid == (string)cb.Tag)
						{
							cb.Checked = true;
						}
					}
				}
			}
		}
	}
}
